package com.itheima.youdianda.controller;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.youdianda.common.R;
import com.itheima.youdianda.pojo.YddUser;
import com.itheima.youdianda.service.YddUserService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("ydd_user")
@Slf4j
public class YddUserController {
    @Autowired
    private YddUserService userService;

    //用户详情
    @GetMapping("rowInfo")
    public R<YddUser> rowInfo(int id){
        log.info("{}",id);
        YddUser byId = userService.getById(id);
        return R.success(byId);
    }
    //用户列表
    @GetMapping("list")
    public R<Map> list(Integer sex,String username,String mobile ,int page,int limit){
        Page<YddUser> ipage=new Page<>(page,limit);
        //条件查询
        LambdaUpdateWrapper<YddUser> wrapper=new LambdaUpdateWrapper<>();
        wrapper.like(ObjectUtil.isNotEmpty(sex),YddUser::getSex,sex);
        wrapper.like(ObjectUtil.isNotEmpty(username),YddUser::getUsername,username);
        wrapper.like(ObjectUtil.isNotEmpty(mobile),YddUser::getMobile,mobile);
        //
        ipage=userService.page(ipage,wrapper);
        //封装
        SysUserIpage userIpage=new SysUserIpage();
        HashMap map=new HashMap();
        long total = ipage.getTotal();
        map.put("count", Convert.toInt(total));
        map.put("totalPages",Convert.toInt(ipage.getTotal()/limit+2));
        map.put("pageSize",limit);
        map.put("currentPage",page);
        map.put("data",ipage.getRecords());
       /* userIpage.setRecords(new HashMap().put("data",));
        //当前页面
        userIpage.setCurrenPage(page);
        //页面条数
        userIpage.setPageSize(limit);
        //
        userIpage.setCount(page*limit);
        userIpage.setTotalPages(ipage.getTotal());*/
        return R.success(map);
    }

    //新增
    @PostMapping("add")
    public R<String> add(@RequestBody YddUser yddUser){
        //设置假数据来填补

        userService.save(yddUser);
        return R.success("成功");
    }


    //删除数据
    @GetMapping("del")
    public R<String> del(Integer id){
        LambdaUpdateWrapper<YddUser>wrapper=new LambdaUpdateWrapper<>();
        wrapper.eq(ObjectUtil.isNotEmpty(id),YddUser::getId,id);
        userService.remove(wrapper);
        return R.success("成功");
    }

    //数据修改
    @PostMapping("update")
    public R<String> update(@RequestBody YddUser yddUser){
        userService.updateById(yddUser);
        return R.success("成功");
    }

}

@Data
class SysUserIpage{
    Map count;
    Map totalPages;
    Map pageSize;
    Map currenPage;
    protected Map records;

}
